package com.starinside.wp.service.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.starinside.wp.foundation.dto.AreaSettingDTO;
import com.starinside.wp.service.PortalService;
import com.starinside.wp.utils.ModelUtil;
import com.starinside.wp.utils.RedisUtil;
import com.starinside.wp.utils.RemoteCallUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class PortalServiceImpl implements PortalService {

    @Value("${sso.server.url}")
    private String ssoServerUrl;

    @Autowired
    RedisUtil redisUtil;

    private static final String MP_APPID = "MP_APPID";
    private static final String MP_APPSECRET = "MP_APPSECRET";
    private static final String MP_TEMPLATE_IDS = "MP_TEMPLATE_IDS";

    @Override
    public String getMPAppId(String areaId) {
        if(StringUtils.isBlank(areaId)){
            return null;
        }

        AreaSettingDTO as = getAreaSetting(MP_APPID, areaId);
        if(as == null || StringUtils.isEmpty(as.getValue())) {
            return null;
        }
        return as.getValue();
    }

    @Override
    public String getMPAppSecret(String areaId) {
        if(StringUtils.isBlank(areaId)){
            return null;
        }

        AreaSettingDTO as = getAreaSetting(MP_APPSECRET, areaId);
        if(as == null || StringUtils.isEmpty(as.getValue())) {
            return null;
        }
        return as.getValue();
    }

    @Override
    public Map<String, String> getMpTemplateIds(String areaId) {
        AreaSettingDTO as = getAreaSetting(MP_TEMPLATE_IDS, areaId);
        if(as == null || StringUtils.isEmpty(as.getValue())) {
            return null;
        }
        String json = as.getValue();
        Map jsonObject = JSON.parseObject(json, HashMap.class);

        return jsonObject;
    }

    @Override
    public AreaSettingDTO getAreaSetting(String key, String areaId) {
        final String  GLOBAL_SETTING = "milepost_item";
        return getAreaSetting(key, GLOBAL_SETTING, areaId);
    }

    public AreaSettingDTO getAreaSetting(String label, String type,  String areaId) {
        return RemoteCallUtil.call(ssoServerUrl + "/api/sso/other_system/getAreaSetting",
                ImmutableMap.of("label",label,"type",type,"areaId",areaId),
                null, AreaSettingDTO.class, "调用sso推送消息出错");
    }
}
